package com.freeLearning.boot.system.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.freeLearning.boot.common.annotation.Log;
import com.freeLearning.boot.common.enums.LogModuleEnum;
import com.freeLearning.boot.common.result.Result;
import com.freeLearning.boot.common.enums.AuditStatusEnum;
import com.freeLearning.boot.core.security.util.SecurityUtils;
import com.freeLearning.boot.shared.mail.service.MailService;
import com.freeLearning.boot.system.enums.MessageEnum;
import com.freeLearning.boot.system.mapper.ConsultantAuditHistoryMapper;
import com.freeLearning.boot.system.model.entity.ConsultantAudit;
import com.freeLearning.boot.system.model.entity.ConsultantAuditHistory;
import com.freeLearning.boot.system.model.entity.Message;
import com.freeLearning.boot.system.model.entity.User;
import com.freeLearning.boot.system.model.form.UserForm;
import com.freeLearning.boot.system.model.query.ConsultantAuditPageQuery;
import com.freeLearning.boot.system.model.vo.ConsultantAuditPageVO;
import com.freeLearning.boot.system.model.vo.ConsultantAuditVO;
import com.freeLearning.boot.system.service.ConsultantAuditService;
import com.freeLearning.boot.system.service.ConsultantDocumentService;
import com.freeLearning.boot.system.service.MessageService;
import com.freeLearning.boot.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "16.咨询师审核接口")
@RequestMapping("/api/v1/consultant/audit")
@RestController
@RequiredArgsConstructor
public class ConsultantAuditController {

    private final ConsultantAuditService consultantAuditService;
    private final ConsultantAuditHistoryMapper consultantAuditHistoryMapper;
    private final UserService userService;
    private final ConsultantDocumentService consultantDocumentService;
    private final MailService mailService;
    private final MessageService messageService;
    @Operation(summary = "分页查询咨询师审核")
    @PostMapping("/page")
    @Log(value = "分页查询咨询师审核", module = LogModuleEnum.CONSULTANTAUDIT)
    public Result<IPage<ConsultantAuditPageVO>> getConsultantAuditPage(@RequestBody ConsultantAuditPageQuery consultantAuditPageQueryParams) {
        IPage<ConsultantAuditPageVO> result = consultantAuditService.getPage(consultantAuditPageQueryParams);
        return Result.success(result);
    }

    @Operation(summary = "审核咨询师")
    @PostMapping("/update-status")
    @Log(value = "审核咨询师", module = LogModuleEnum.CONSULTANTAUDIT)
    public Result<Boolean> updateConsultantAuditStatus(@RequestBody ConsultantAudit consultantAudit) {
        consultantAudit.setAuditTime(LocalDateTime.now());
        boolean updateStatus = consultantAuditService.updateById(consultantAudit);
        ConsultantAuditHistory consultantAuditHistory = BeanUtil.copyProperties(consultantAudit, ConsultantAuditHistory.class);
        consultantAuditHistory.setId(null);
        consultantAuditHistoryMapper.insert(consultantAuditHistory);
        User user = userService.getOne(new QueryWrapper<User>().eq("id", consultantAudit.getConsultantId()));
        if (AuditStatusEnum.AUDIT_PASS.getValue().equals(consultantAudit.getStatus())){
            user.setStatus(1);
            userService.updateById(user);
        }

        if (!user.getEmail().isEmpty()){
            mailService.sendHTMLMail(
                    user.getEmail(),
                    AuditStatusEnum.getLabel(consultantAudit.getStatus()),
                    getFormattedMailContent(consultantAudit),
                    false
            );
        };
        StringBuilder messageContent = new StringBuilder("您的信息");
        if (consultantAudit.getStatus().equals(AuditStatusEnum.AUDIT_PASS.getValue())){
            messageContent.append("审核通过，");
        } else {
            messageContent.append("审核不通过");
        }
        messageContent.append("审核意见：");
        messageContent.append(consultantAudit.getOpinion());
        Long userId = SecurityUtils.getUserId();
        Message message = Message.builder()
                .title(consultantAudit.getStatus().equals(AuditStatusEnum.AUDIT_PASS.getValue()) ? "审核通过" : "审核不通过")
                .content(messageContent.toString())
                .type(consultantAudit.getStatus().equals(AuditStatusEnum.AUDIT_PASS.getValue()) ? MessageEnum.INFO_AUDIT_PASS.getValue() : MessageEnum.INFO_AUDIT_NOT_PASS.getValue())
                .publisherId(userId)
                .publishTime(LocalDateTime.now())
                .createBy(userId)
                .acceptId(consultantAudit.getConsultantId())
                .other(JSONUtil.toJsonStr(consultantAudit))
                .build();
        messageService.sendMessage(message);
        return Result.success(updateStatus);
    }

    @Operation(summary = "获取咨询师审核历史")
    @GetMapping("/history/{id}")
    public Result<List<ConsultantAuditHistory>> getConsultantAuditHistory(@PathVariable Integer id) {
        List<ConsultantAuditHistory> history = consultantAuditHistoryMapper.selectList(new QueryWrapper<ConsultantAuditHistory>().eq("consultant_id", id).orderByAsc("audit_time"));
        return Result.success(history);
    }

    @Operation(summary = "查询审核师资料")
    @GetMapping("/get-consultant-data/{id}")
    public Result<ConsultantAuditVO> getAuditData(@PathVariable Long id) {
        UserForm userInfo = userService.getUserFormData(id);
        ConsultantAuditVO consultantAuditVO = BeanUtil.copyProperties(userInfo, ConsultantAuditVO.class);
        ConsultantAudit auditInfo = consultantAuditService.getOne(new QueryWrapper<ConsultantAudit>().eq("consultant_id", id));
        consultantAuditVO.setAuditStatus(auditInfo.getStatus());
        consultantAuditVO.setAuditTime(auditInfo.getAuditTime());
        consultantAuditVO.setOpinion(auditInfo.getOpinion());
        consultantAuditVO.setConsultantId(auditInfo.getConsultantId());
        consultantAuditVO.setAuditorId(auditInfo.getAuditorId());
        consultantAuditVO.setAuditorName(auditInfo.getAuditorName());
        return Result.success(consultantAuditVO);
    }
    private String getFormattedMailContent(ConsultantAudit consultantAudit) {
        StringBuilder content = new StringBuilder();
        content.append("<html><body style='font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>");
        content.append("<div style='background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'>");

        // 添加平台Logo和标题
        content.append("<img src='http://www.free-learning.icu/images/logo.png' alt='公益性教育咨询平台' style='width: 150px; height: auto; display: block; margin: 0 auto;'><br>");
        content.append("<h1 style='color: #333333; text-align: center;'>审核结果通知</h1>");

        // 用户问候
        content.append("<p style='color: #666666;'>尊敬的咨询师：</p>");
        content.append("<p style='color: #666666;'>您的个人信息审核结果如下：</p>");

        // 审核状态、意见和审核人
        content.append("<p style='color: #666666;'><strong style='color: #333333;'>审核状态：</strong>").append(AuditStatusEnum.getLabel(consultantAudit.getStatus())).append("</p>");
        content.append("<p style='color: #666666;'><strong style='color: #333333;'>审核意见：</strong>").append(consultantAudit.getOpinion()).append("</p>");
        content.append("<p style='color: #666666;'><strong style='color: #333333;'>审核人：</strong>").append(consultantAudit.getAuditorName()).append("</p>");

        // 动态提示信息
        if (consultantAudit.getStatus().equals(AuditStatusEnum.AUDIT_PASS.getValue())) {
            content.append("<p style='color: #28a745;'>恭喜您，审核通过！您可以退出重新登录开始维护课程。</p>");
        } else {
            content.append("<p style='color: #dc3545;'>审核未通过，请根据审核意见进行修改。</p>");
        }

        // 平台信息和链接
        content.append("<p style='color: #666666;'>感谢您使用我们的服务！如果您有任何疑问，请访问我们的官网：<a href='http://www.free-learning.icu/' style='color: #007bff;'>公益性教育咨询平台</a></p>");
        content.append("<p style='color: #666666;'>祝您使用愉快！</p>");

        content.append("</div>");
        content.append("</body></html>");
        return content.toString();
    }
}
